<!--<template>
    <div class="m-window">
            <el-row :gutter="10" style="margin:8px auto;">
                <el-col :span="2">
                    <el-button type="primary" @click="backtrack">返回</el-button>
                </el-col>
            </el-row>
            <browse-contract
                :account="account"
                :applyId="applyId"/>
        </div>
</template>
<style lang="less" scoped>
    .m-window{
        overflow: auto;
        overflow-x: hidden;
    }
</style>
<script>
import { mapState,mapActions } from 'vuex'

export default {
    props:['pageSourceCode'],
    data(){
        return {
            account:'',
            applyId:'',
            checkTab:''
        }
    },
    created() {
        this.account = 'szlsbl'//联塑保理电子签账号
        this.applyId = this.supplyChainFinance.role.ID
    },
    computed: {
        ...mapState(['supplyChainFinance'])
    },
    methods:{
         ...mapActions([
            'changeTOdo',
            'changeMyProcessedCTCode'
        ]),
        backtrack(){
            if(this.pageSourceCode == 'myProcessed'){
                this.changeMyProcessedCTCode('')
            }else{
                this.changeTOdo({isMyToDoList:0})
            }            
        }
    }
}
</script>-->
<template>
    <div class="m-window">
         <el-row :gutter="10" style="margin:8px auto;">
            <el-col :span="2" v-show="pageSourceCode != 'applyShortTable'">
                <el-button type="primary" @click="backtrack">返回</el-button>
            </el-col>
        </el-row>
        <h2>流程编号：<b>{{processNumber}}</b></h2>
        <el-row type="flex" justify="center" v-show="pageCode!='read'">
            <el-col :span="24">
                <el-steps :active="stepsActive" align-center finish-status="success">
                    <el-step title="供应商签署"></el-step>
                    <el-step title="金融签署"></el-step>
                    <el-step title="签署完成"></el-step>
                </el-steps>
            </el-col>
        </el-row>
        <el-row>
            <el-col>
                <p v-if="pageCode=='read'">您有以下合同待阅读</p>
                <p v-else>您有以下合同</p>
                <ul class="file-col">
                    <li v-for="(v,i) in contractList" :key="i">
                        <a href="javascript:;" v-text="`${i+1}. ${v.name}`"></a>
                        <el-button class="mini" @click="previewContract(v)">预览</el-button>
                        <el-button class="mini" @click="downloadFile(v)">下载</el-button>
                    </li>
                </ul>
            </el-col>
        </el-row>
        <el-row class="step1" v-show="pageCode=='read'">
            <el-col>
                <el-checkbox label="已阅读并理解以上合同" name="type" v-model="isRead"></el-checkbox>
            </el-col>
            <el-col :span="2">
                 <el-button type="primary" @click="nextStep">下一步</el-button>
            </el-col>
        </el-row>
        <el-row class="step2" v-show="pageCode=='sign'">
            <el-col style="margin-bottom:10px;">
                <p>请签署《保理服务合同》和《应收账款转让通知函》。</p>
            </el-col>
            <el-col :span="2">
                 <el-button type="primary" @click="sign">签署</el-button>
            </el-col>
        </el-row>
        <el-row class="step3" v-show="pageCode=='signComplete'">
            <el-col>
                <p>签署《保理服务合同》和《应收账款转让通知函》成功。</p>
            </el-col>
        </el-row>
        <!-- 预览合同 -->
        <el-dialog
            title="合同预览"
            :visible.sync="previewDialogVisible"
            width="99%"
            class="contract-dialog"
            center>
            <div class="preview-col" v-loading="loading">
                <iframe :src="contractSrc" height="100%" width="100%" frameborder="0"></iframe>  
            </div>
        </el-dialog>
        <!-- 签署验证码 -->
        <el-dialog
            class="sign-dialog"
            title="签署校验"
            :visible.sync="signDialogVisible"
            width="30%"
            center>
            <el-row type="flex" justify="center">
                <el-col class="verify-col">
                    <label>验证码：</label>
                    <input type="text" v-model.trim="vCode">
                    <el-button @click="acquireVerifyCode">{{verifyCodeBtnText}}</el-button>
                </el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-col :span="5">
                    <el-button type="primary" @click="onSubmit" style="margin-top:30px;">确认</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>
<style lang="less" scoped>
    .m-window{
        overflow: auto;
        overflow-x: hidden;
        .contract-dialog{
            /deep/ .el-dialog{
                height: 80%;
                .el-dialog__body{
                    height: 100%;
                    padding: 0 !important;
                    margin: 25px 0 !important;
                }
            }
            .preview-col{
                height: 100%;
                width: 100%;
            }
        }
        .file-col {
            padding-left: 20px;
            li{
                margin: 10px 0;
            }
        }
        /deep/.el-button.mini{
            height:20px !important;
            width:50px !important;
            line-height:20px !important;
            padding: 0 !important;
        }
        .sign-dialog {
            .verify-col{
                display: flex;
                flex-direction: row;
                justify-content: center;
                input{
                    display: block;
                    width: 100px;
                    border:none;
                    outline-style: none;
                    border-bottom:1px solid #ccc;
                }
                /deep/.el-button{
                    height:20px !important;
                    width:80px !important;
                    line-height:20px !important;
                    padding: 0 !important;
                    margin-left: 8px;
                }
            }
        }
    }
</style>

<script>
import { mapState,mapActions } from 'vuex'
import { showAlert } from "lesso-common/public/utils"
import { download } from '@/util/fileDownload.js'
import eventBus from '@/util/event-bus'
export default {
    props:{
        applyId:String,
        pageSourceCode:String
    },
    data() {
        return {
            previewDialogVisible:false,
            signDialogVisible:false,
            verifyCodeBtnText:'获取验证码',
            pageCode:'read', //阅读 read 、签署 sign、签署完成 signComplete
            loading:false,            
            contractReadNum:0,
            stepsActive:1,
            isRead:false,
            account:'',
            apply_id:'',
            checkTab:'',
            processNumber:'',
            contractSrc:'',
            contractList:[],
            alreadyContract:[],
            vCode:'',
            docIdList:[],
            isSign:false,
            timer:null
        }
    },
    created() {
        this.account = 'szlsbl'//联塑保理电子签账号 
        this.apply_id = this.applyId || this.supplyChainFinance.role.ID
        this.validatesSignedContract()
        this.loadContract()
    },
    mounted(){
        eventBus.$on('closeTab',(tab)=>{
            if((tab.content == 'applyList' && this.supplierApplyList.pageCode == 'signPreview') 
            || (tab.content == 'myToDoList' && this.supplyChainFinance.isMyToDoList == 'act_cust_sign')){
                 showAlert({
                    msg: `提示：您的合同尚未签署！`,
                    type: 2
                })
            }
        })
    },
    watch:{
       isRead:function(val, oldVal){
           if(this.alreadyContract.length!=this.contractList.length){
                this.isRead = false
                let notReadContracts = ''
                for(let i=0,data = this.contractList;i<data.length;i++){
                    if(!this.alreadyContract.includes(data[i].name)){
                        notReadContracts = `${notReadContracts} ${data[i].name}`
                    }
                }
                showAlert({
                    msg: `您还有:${notReadContracts}合同，未阅读！`,
                    type: 2
                })
           }
       },
       signDialogVisible:function(val,oldVal){
           if(!val){
             clearInterval(this.timer)
             this.verifyCodeBtnText = '获取验证码'
           }
       }
    },
    computed: {
        ...mapState([
            'supplierApplyList',
            'supplyChainFinance'
        ])
    },
    methods: {
         ...mapActions([
            'changeTOdo',
            'changePageCode',
            'changeMyProcessedCTCode'
        ]),
        //查询合同是否签署
        async validatesSignedContract(){
            let that = this
            await this.$http.validatesSignedContract({
                applyId:this.apply_id,
                eSignAccount:this.account
            }).then(({data})=>{
                that.isSign = data.code == 200? true : false
                that.pageCode = data.code == 200? 'signComplete' : 'read'
            })
            .catch((error)=>{
                this.$alert("查询是否签署失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            })
        },
        //获取验证码
        async getVerifyCode(){
            let that = this
            await this.$http.getVerifyCode({
                applyId:this.apply_id,
                eSignAccount:this.account
            }).then(({data})=>{
                if(data.code == 200){
//                    this.$message({
//                        message: data.info,
//                        type: 'success'
//                    })
                    that.$message({
                    message: data.info,
                    type: 'success',
                    center: true
                    });
                    let second = 60
                    clearInterval(that.timer)
                    that.timer = setInterval(function(){
                        if(second>0){
                            that.verifyCodeBtnText = `${--second}秒后失效`
                        }else{
                            clearInterval(that.timer)
                            that.verifyCodeBtnText = '重新获取'
                        }
                    },1000)          
                }else{
//                   showAlert({
//                        msg: data.info,
//                        type: 0
//                    }) 
                    that.$message({
                        message: data.info,
                        type: 'warning',
                        center: true
                    });
                }                
            })
            .catch((error)=>{
                this.$alert("查询失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            })
        },
        //获取合同数据
        async loadContract(docId){
            this.loading = true
            let that = this
            let param = {
                account:this.account,
                applyId:this.apply_id
            }
            await this.$http.createToken(param).then(({data})=>{
                if(data.code == 200 && data.rows.contractList){
                    let token = data.rows.token
                    if(docId){
                         data.rows.contractList.forEach(function(value, index, array) {
                            if(value.docId == docId){
                                that.contractSrc = `https://esign.lesso.com/testesign/SSOSign/SignLogin?param=${token}&url=https://esign.lesso.com/TestEsign/Sign/indexView?doc_id=${value.docId}`
                            }
                        })
                    }else{
                        that.processNumber = data.rows.contractList.length>0? data.rows.contractList[0]['itemNo'] : ''
                        that.contractList = data.rows.contractList || []
                    }
                }
                setTimeout(function(){
                    that.loading = false
                },600)
            })
            .catch((error)=>{
                this.$alert("查询失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            })
        },
        //一键签署合同
        async oneKeySignContract(){
            const loading = this.$loading({
                lock: true,
                text: '合同签署中，请稍后...',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,.9)'
            })
            let parame = {
                applyId:this.apply_id,
                vCode:this.vCode,
                docIdList:this.docIdList,
                eSignAccount:this.account
            }
            await this.$http.oneKeySignContract(parame).then(({data})=>{
                let that = this
                setTimeout(function(){
                    loading.close()
                    if(data.code == 200){
                        showAlert({
                            msg: data.info,
                            type: 1
                        })
                        that.signDialogVisible = false
                        that.pageCode = 'signComplete'
                        that.vCode = ''
                        that.stepsActive = 2
                        that.isSign = true                    
                    }else{
                    showAlert({
                            msg: data.info,
                            type: 0
                        }) 
                    } 
                },800)         
            })
            .catch((error)=>{
                this.$alert("查询失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            })
        },
        onSubmit(){
            if(!this.vCode){
                this.$message({
                    message: '验证码不能为空',
                    type: 'warning'
                })
                return
            }
            this.oneKeySignContract()
        },
        //获取验证码
        acquireVerifyCode(){
            this.verifyCodeBtnText = '重新获取'
            this.getVerifyCode()
        },
        //下载合同文件
        downloadFile(v){
            this.fileDownload(v.name,v.path)
        },
        //签署
        sign(){
            this.verifyCodeBtnText = '获取验证码'
            this.vCode = ''
            this.signDialogVisible = true
        },
        //预览合同
        previewContract(v){
            if(!this.alreadyContract.includes(v.name)){
                this.docIdList.push(v.docId)
                this.alreadyContract.push(v.name)
            }
            this.contractSrc = 'about:blank'
            this.loadContract(v.docId)
            this.previewDialogVisible = true
        },
        //下一步
        nextStep(){
            if(!this.isRead){
                 showAlert({
                    msg: "请勾选“已阅读并理解以上文件”",
                    type: 2
                })
                return
            }
            this.pageCode = 'sign'
            this.stepsActive = 1
        },
        //返回
        backtrack(){
            //阅读 read 、签署 sign、签署完成 signComplete
            if(this.pageCode=='read'){
                if(!this.isSign){
                    this.$confirm("您的合同尚未签署，确认离开吗？", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消"
                    }).then(() => {
                        if(this.pageSourceCode == 'myProcessed'){
                            this.changeMyProcessedCTCode('')
                        }else{
                            this.changeTOdo({isMyToDoList:0})
                        }
                    }).catch(() => {
                        
                    })
                }                
               
            }else if(this.pageCode == 'sign'){
               this.pageCode = 'read' 
            } else{
                if(this.pageSourceCode == 'myProcessed'){
                    this.changeMyProcessedCTCode('')
                }else{
                    this.changeTOdo({isMyToDoList:0})
                }
            }
        },
        fileDownload(filename,url){
           this.$http.getFullFilePath({
            'url': url
            }).then(({ data }) => {
                if (data.code == 200) {
                    download(`${filename}.pdf`,data.rows[0].fileName)
                } else {
                    showAlert({
                        msg: `操作失败：${data.info}`,
                        type: 0
                    })
                }
            })
            .catch((error) => {
                showAlert({
                    msg: `查询失败，请检查网络！`,
                    type: 0
                })
            })
       }
    }
}
</script>

